import React, { Component } from 'react'
import { history } from '@/index'
import SearchForm from '@/Public/PubTable/searchForm'
import BaseTable from '@/Public/PubTable/baseTable'
import WrappedTable from '@/Public/PubTable/WrappedTable'
import { mallTableConfig } from '@/Public/PubTable/pageColumns'
import { mallManagement } from '@/Utils/Urls'
import { downloadTemplate, uploadBooks, reshowBook, getBookDetail } from './ActionCreators'
import { changeGoodsStatus, detailData } from '@/Redux/ActionTypes/MallManagement/MallManagementActionCreators'
import { selectedData } from '@/Redux/ActionTypes/public/BaseTable/publicActionCreator'
import { ExclamationCircleOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import { Tabs, Space, Button, message, Modal, Upload } from 'antd';
import './index.css'

const { confirm } = Modal
const { TabPane } = Tabs;
const markName = 'mallTable'

const mapStateToProps = (state) => ({
  title: state.mallManagement.mall_title,
})

const mapDispatchToProps = (dispatch) => ({
  changeGoodsStatus(...rest) {
    return dispatch(changeGoodsStatus(...rest))
  },
  setSelectedData(...rest) {
    return dispatch(selectedData(...rest))
  },
  setDetailData(...rest) {
    return dispatch(detailData(...rest))
  }
})

@WrappedTable.create(markName)
@connect(mapStateToProps, mapDispatchToProps)
class mallTable extends Component {
  state = {
    selectedNodeMsg: {},    // 选中的树节点的信息
    remove: 0,
    typeId: 0,
    queryType: 0
  }

  createSearchFormConfig() {
    return ({
      formItems: [
        {
          type: 'Extra',
          name: 'buttonList',
          render: saerchFormRef => {
            return (
              <Space style={this.props.title === '订单管理' ? { display: 'none' } : ''}>
                <Button onClick={() => this.divideBooks('default')} className='btn-danger'>
                  默认排序
                </Button>
                <Button onClick={() => this.divideBooks('sell')} className='btn-danger'>
                  销量排序
                </Button>
                <Button onClick={() => this.divideBooks('view')} className='btn-danger'>
                  浏览量排序
                </Button>
                {/* <Button onClick={this.removeBook} className='btn-danger'>
                    删除
                  </Button> */}
                <Button onClick={() => this.showConfirm()} className='btn-danger'>
                  <DownloadOutlined />表格模板
                </Button>
                <Upload customRequest={file => this.upload(file)} showUploadList={false}>
                  <Button>
                    <UploadOutlined /> 导入表格
                  </Button>
                </Upload>
                <Button onClick={() => { this.addGoods() }} className='btn-danger'>
                  添加单个商品
                </Button>
              </Space>
            )
          }
        },
      ],
      ajaxConfig: {
        url: mallManagement.getBooks + `/${this.state.typeId}/${this.state.remove}/${this.state.queryType}`,
        ajaxType: 'post',
      }, withoutSearchButton: true
    }
    )
  }

  changeTableData(res) {
    return {
      data: res.list,
      pageSize: 10,
      current: res.currentPage,
      total: res.totalCount
    }
  }

  changeSearchLimit = data => {
    const { selectedNodeMsg } = this.state;

    if (JSON.stringify(selectedNodeMsg) !== '{}' && selectedNodeMsg['id'] !== -1) {
      data['id'] = selectedNodeMsg['id']
    }
    return data;
  }

  tabChange(e) {
    let restParam = {
      remove: e === '1' ? 0 : 1,
      typeId: 0
    }

    this.setState({
      ...restParam
    })
  }

  operationButton(record) {
    return this.state.remove === 0 ? <Button onClick={() => this.updateBook(record)}>编辑</Button> : <Button onClick={() => this.reshowBook(record)}>重新上架</Button>
  }


  render() {
    return (
      <WrappedTable className="mall-table">
        <div className='mall-table-search'>
          <Tabs defaultActiveKey="1" onChange={(e) => this.tabChange(e)}>
            <TabPane tab="售卖中" key="1">
            </TabPane>
            <TabPane tab="已下架" key="2">
            </TabPane>
          </Tabs>
        </div>
        <SearchForm
          formItems={this.createSearchFormConfig()}
          changeSearchLimit={this.changeSearchLimit}
          changeTableData={this.changeTableData}
          markName={markName}
        ></SearchForm>
        <BaseTable
          markName={markName}
          tableConfig={mallTableConfig} // 表格表头设置
          changeTableData={this.changeTableData} // 把拿到的表格数据改造成符合公共组件所需数据的格式
          changeSearchLimit={this.changeSearchLimit}
          stylePointer={true}
          onRowEvent={true}
          operationButton={record => this.operationButton(record)}
        ></BaseTable>
      </WrappedTable>
    )
  }

  refreshTable() {
    this.props.pub_getAllData()
  }

  divideBooks(type) {
    let queryType = 0
    if (type === 'default') {
      queryType = 0
    } else if (type === 'sell') {
      queryType = 1
    } else {
      queryType = 2
    }
    this.setState({
      queryType
    })
  }

  async reshowBook(record) {
    const res = await reshowBook(record.id)
    if (res.data.success) {
      message.success('上架成功')
      this.refreshTable()
    } else {
      message.error('上架失败')
    }
  }

  async updateBook(record) {
    this.props.setSelectedData(record)
    this.props.changeGoodsStatus('update')
    const bookRes = await getBookDetail(record.id)
    const value = bookRes.data.data
    this.props.setDetailData(value)
    history.push('/homePage/mallManagement/goods/goodsInfo')
  }

  showConfirm() {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `确定下载EXCEL模板表格吗`,
      onOk: () => {
        message.info('模板正在下载，请稍等片刻！')
        downloadTemplate().then(() => {
          this.refreshTable()
          message.success('成功下载模板')
        }).catch(() => {
          message.error('下载模板失败')
        })
      }
    });
  }

  upload(options) {
    uploadBooks(options.file).then(res => {
      if (res.data.success) {
        message.success('成功导入')
        this.refreshTable()
      }else{
      message.error('导入失败')
      }
    }).catch(() => {
      message.error('导入失败')
    })
  }

  addGoods() {
    this.props.changeGoodsStatus('new')
    history.replace('/homePage/mallManagement/goods/goodsInfo')
  }
}

export default mallTable